<?php
/**
 * SettingModel.php
 * 网站配置数据
 * @author Life <349865361@qq.com>
 * @version 20140110
 */
class SettingModel extends BaseModel
{
    /**
     * 保存系统配置信息
     * @param array $array 配置信息数组
     */
    public function setConfig($array)
    {
        if (empty($array) || !is_array($array)) {
            return false;
        }
        $config_array = array();
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $k => $v) {
                    $config_array["config['" . $key . "']['" . $k . "']"] = $v;
                }
            } else {
                $config_array["config['" . $key . "']"] = $value;
            }
        }
        $config_base_files = glob(ROOT_PATH . 'inc/base/*.ini.php');
        $config_site_files = glob(ROOT_PATH . 'inc/config/*.ini.php');
        $config_files = array_merge((array) $config_base_files, (array) $config_site_files);
        if (!empty($config_files)) {
            foreach ($config_files as $config_file) {
                $config = file_get_contents($config_file); //读取配置
                foreach ($config_array as $name => $value) {
                    $name = str_replace(array(
                        "'",
                        '"',
                        '[',
                        '*'
                    ), array(
                        "\\'",
                        '\"',
                        '\[',
                        '\*'
                    ), $name); //转义特殊字符，再传给正则替换
                    if (is_string($value) && !in_array($value, array(
                        'true',
                        'false',
                        '3306'
                    ))) {
                        if (!is_numeric($value)) {
                            $value = "'" . $value . "'"; //如果是字符串，加上单引号
                        }
                    }
                    $config = preg_replace("/(\\$" . $name . ")\s*=\s*(.*?);/iU", "$1={$value};", $config); //查找替换
                }
                // 写入配置
                if (!@file_put_contents($config_file, $config)) {
                    return false;
                }
            }
        }
        return true;
    }
}